from django import http
from django.shortcuts import render

# Create your views here.
from django.utils.timezone import localdate
from django.views import View

from contents.utils import get_categories
from goods.models import GoodsCategory, SKU, GoodsVisitCount
# from django.core.paginator import Paginator
from django.core.paginator import Paginator

from goods.utils import get_breadcrumb
from utils.response_code import RET


class ListView(View):
    def get(self,request,category_id,page_num):
        #获取分类信息
        category_data=get_categories()

        ##获取前端传过来的关键字
        sort=request.GET.get('sort','default')
        if sort=='default':
            sort_key='-create_time'
        elif sort=='price':
            sort_key='price'
        elif sort=='hot':
            sort_key='-sales'


        #获取面包屑
        data={
            "cat1":{},
            "cat2":{},
            "cat3":{}
        }
        cat3=GoodsCategory.objects.get(id=category_id)
        data['cat3']['name']=cat3.name
        data['cat2']['name']=cat3.parent.name
        data['cat1']['name']=cat3.parent.parent.name
        data['cat1']['url']=cat3.parent.parent.goodschannel_set.first().url

        #获取到所有的商品
        sku_all = SKU.objects.filter(category_id=category_id, is_launched=True).order_by(sort_key)

        #对商品进性分页
        #定义每页多少个商品
        per_page=5
        #所有页
        pages=Paginator(sku_all,per_page)
        #指定页
        page=pages.page(page_num)
        #总页数
        total_page=pages.num_pages
        #当前页
        current_page=page.number
        #当前页商品列表
        sku_list=page.object_list

        context={
            "categories":category_data,
            "breadcrumb":data,
            'sku_list':sku_list,
            'current_page':current_page,
            'total_page':total_page,
            "category_id":category_id,
            'sort':sort,
        }


        return render(request, 'list.html', context=context)

class HotGoodsView(View):
    def get(self,request,category_id):
        #获取热销产品
        #1.初始化数据
        try:
            cat=GoodsCategory.objects.get(id=category_id,)
        except Exception as e:
            return http.JsonResponse({{'code':RET.PARAMERR,'errmsg':'分类ID错误'}})

        #2.处理业务逻辑
        skus=SKU.objects.filter(category_id=category_id).order_by('-sales')[0:2]

        hot_skus=[]
        for sku in skus:
            sku_data={
                "id":sku.id,
                "default_image_url":sku.default_image_url.url,
                "name":sku.name,
                "price":sku.price
            }
            hot_skus.append(sku_data)

        #3.返回响应
        res={
            'code':RET.OK,
            'errmsg':'成功',
            'hot_skus':hot_skus
        }
        return http.JsonResponse(res)
        pass

class DetailView(View):
    def get(self,request,sku_id):
        #获取商品详情页
        #1.初始化数据
        try:
            sku=SKU.objects.get(id=sku_id)
        except Exception as e:
            pass

        #2.处理业务逻辑
        #获取分类信息
        categories=get_categories()
        #获取面包屑信息
        breadcrumb=get_breadcrumb(sku.category_id)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        #3.返回响应suod
        context={
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sku':sku,
            'specs':goods_specs,
        }
        return render(request,'detail.html',context=context)
        pass

class DetailVisitView(View):
    """详情页分类商品访问量"""

    # 统计一下分类的访问量
    # 1.初始化数据
    def post(self, request, category_id):
        try:
            cat = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return http.JsonResponse({'code': RET.PARAMERR, 'errmsg': '分类id错误'})
            # 2.处理业务逻辑
            # 2.1先查看今天是否有当天的记录
        now_date = localdate()

        try:
            # 2.2如果有记录，就累加
            goods_visit_count = GoodsVisitCount.objects.get(data=now_date, category_id=category_id)
            goods_visit_count.count += 1
            goods_visit_count.save()
        except Exception as e:
            # 2.3如果没有就重新创建一个
            goods_visit_count = GoodsVisitCount.objects.create(
                date=now_date,
                category_id=category_id,
                count=1
            )
        # 3.返回响应
        res = {
            'code': RET.OK,
            'errmsg': '成功'
        }
        return http.JsonResponse(res)


